<template>
  <div class="ddcr">
    <div class="history-curve">
      <div class="info">
        <div class="title">断电撤人</div>
        <el-date-picker class="time-picker" v-model="searchData.timeRange" start-placeholder="开始时间"
          end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange" />
        <div class="info-item">
          <span>人数曲线：</span>
          <el-switch v-model="searchData.peopleSwitch" />
        </div>
        <div class="info-item">
          <span>矿井供电：</span>
          <el-tag type="primary" size="large">正常</el-tag>
        </div>
      </div>

      <div class="content">
        <div class="left">
          <el-checkbox-group class="my-checkbox" v-model="searchData.checkedCdCode">
            <el-checkbox v-for="item in filterSensorList" :key="item.cdCode" :value="item.cdCode"
              :label="item.areaLocation" />
          </el-checkbox-group>
        </div>
        <!-- 右边图表区 -->
        <BEchart ref="bEchartRef" class="charts" :options="option"></BEchart>
      </div>
    </div>

    <div class="statistics">
      馈电器统计：
      <span class="openCount">{{ statistics.openCount }}</span>
      <span class="closeCount">{{ statistics.closeCount }}</span>
    </div>
  </div>

</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getHisGraph, getKdSensorStatistic } from '@/api/sensor'
import { getNeedShowSensor } from '@/api/alarm'
import { getPersonData } from '@/api/person'
import BEchart from '@/components/b-echart/index.vue'
import { useAuthStore } from '@/store/auth'
import { storeToRefs } from 'pinia'
import { useHistoryCuver } from '@/hooks/useHistoryCurve'
import emiter from '@/utils/mitt'
interface ChartDataItem {
  dateMinute: string
  cdValue: number
  formatter: string
  cdState?: string
  cdStateName?: string
  showValue?: string
  unitCode?: string
  cdLocation?: string
}

interface ChartData {
  cdCode: string
  cdLocation: string
  data: ChartDataItem[]
  sensorType?: string
  maxValue?: number
  minValue?: number
  averageValue?: number
  unitCode?: string
  bjIndexs?: Array<[number, number]>
  bxIndexs?: Array<[number, number]>
}

interface SearchData {
  timeRange: [string, string]
  checkedCdCode: string[]
}

interface AreaLocation {
  cdCode: string
  areaLocation: string
}

const loading = ref(false)
const sensorList = ref<AreaLocation[]>([])
const isMore24Hour = ref(false)
const eChartDataCache = ref<ChartData[]>([])

const searchData = ref<SearchData>({
  timeRange: ['', ''],
  checkedCdCode: [],
  peopleSwitch: true
})

const filterSensorList = computed(() => {
  return sensorList.value
})

const bEchartRef = ref()
const { option, showEChartData, clearECharts, changTooltip } = useHistoryCuver()
const getHisGraphFun = async () => {
  if (!searchData.value.checkedCdCode.length) {
    ElMessage.error('请选择传感器')
    clearECharts()
    return
  }

  if (!searchData.value.timeRange.length) {
    ElMessage.error('请选择开始时间和结束时间')
    clearECharts()
    return
  }

  loading.value = true

  try {
    const { data } = await getHisGraph({
      cdCodes: searchData.value.checkedCdCode,
      startTime: searchData.value.timeRange[0],
      endTime: searchData.value.timeRange[1]
    })
    eChartDataCache.value = data.data
    isMore24Hour.value = data.isMore24Hour

    if (searchData.value.peopleSwitch) {
      const { data: personData } = await getPersonData({
        ...globalParams.value,
        startTime: searchData.value.timeRange[0],
        endTime: searchData.value.timeRange[1],
      })
      const list = personData.dataList.map(item => {
        return {
          cdLocation: '人数曲线',
          cdValue: item.count,
          showValue: item.count + '人',
          dateMinute: item.time
        }
      })
      eChartDataCache.value.push({
        cdLocation: '人数曲线',
        data: list
      })

    }
    showEChartData(eChartDataCache.value)
  } catch (error) {
    clearECharts()
  } finally {
    loading.value = false
  }
}

const statistics = ref({
  openCount: 0,
  closeCount: 0
})
const statisticsList = ref([])
async function getStatistics () {
  const { data } = await getKdSensorStatistic()
  statisticsList.value = data
}

const authStore = useAuthStore()
const { globalParams } = storeToRefs(authStore)
onMounted(async () => {
  getNeedShowSensor(globalParams.value.cdCode).then((res) => {
    sensorList.value = res.data.find(type => type.quotaCode === '002').sensorList
    authStore.setSceneTypeList(sensorList.value)
  })
  searchData.value.timeRange = [globalParams.value.startTime, globalParams.value.endTime]
  searchData.value.checkedCdCode = [globalParams.value.cdCode, '52052301564101KG1011018D09']
  await Promise.all([getStatistics(), getHisGraphFun()])

  watch(
    searchData.value,
    () => {
      getHisGraphFun()
    },
    {
      deep: true
    }
  )
  progressToData(0)
  emiter.on('timeProgress', ({progress}) => progressToData(progress))
})

function progressToData (progress: number) {
  const chartIndex = Math.ceil(eChartDataCache.value[0].data.length * progress / 100)
  changTooltip(bEchartRef.value.chartInstance, chartIndex)
  const statisticsIndex = Math.ceil(statisticsList.value.length * progress / 100)
  statistics.value = statisticsList.value[statisticsIndex]
}

onUnmounted(() => {
  emiter.off('timeProgress')
})
</script>

<style lang="scss" scoped>
.ddcr {
  height: 300px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  background: var(--bg-color-page);
  padding: 8px;
  overflow: hidden;

  .history-curve {
    display: flex;
    flex-direction: column;
    flex: 1;
    height: 100%;
    overflow: hidden;
    gap: 8px;

    .info {
      display: flex;
      align-items: center;
      gap: 16px;
      background: var(--bg-color-page);
      padding: 8px;

      .title {
        min-width: 286px;
        line-height: 35px;
        padding-left: 14px;
        padding-right: 100px;
        height: 35px;
        background-image: url(/src/assets/images/bdialog/title-bg.png);
        background-size: 100% 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-right: 16px;
      }

      .info-item {
        display: flex;
        align-items: center;

        :deep(.el-switch__action) {
          background-color: #fff;
        }
      }

      .sensor-type-checkbox {
        height: 240px;
        overflow-y: auto;
        flex-direction: column;
      }

      .sensor-input {
        width: 180px;
        margin: 0 8px 0 4px;
      }

      .time-picker {
        flex: 1;
        max-width: 300px;
      }
    }

    .content {
      display: flex;
      flex: 1;
      overflow: hidden;
      padding: 8px;
      background: var(--bg-color-page);

      .left {
        margin-top: 8px;
        height: calc(100% - 8px);
        flex-shrink: 0;
        overflow-y: auto;
        padding-right: 16px;

        .my-checkbox {
          flex-direction: column;

          .el-checkbox {
            margin-right: 0;
            color: var(--text-color-placeholder)
          }
        }
      }

      .charts {
        flex: 1;
        overflow: hidden;
      }
    }
  }

  .statistics {
    position: fixed;
    align-items: center;
    bottom: 380px;
    right: 340px;
    padding: 4px 16px;
    font-size: 16px;
    gap: 8px;
    border-radius: 30px;
    background-color: var(--bg-color-page);
    border: 1px solid var(--el-color-primary-light-5);

    .openCount {
      font-weight: bold;
      font-size: 20px;
      position: relative;
      color: var(--el-color-primary);
      text-align: right;

      &:after {
        content: '';
        position: absolute;
        top: 50%;
        right: -8px;
        transform: translateY(-40%);
        width: 1px;
        height: 15px;
        background-color: var(--text-color);
      }
    }

    .closeCount {
      font-weight: bold;
      margin-left: 16px;
      font-size: 20px;
      color: var(--el-color-danger);
      text-align: right
    }

  }
}
</style>
